package controllers

import (
	"beego/comm/auth"
	"beego/comm/cipher"
	"beego/comm/str"
	"beego/comm/utils"
	"fmt"
	"strings"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) GetUserPubKey() {
	beego.Info("================= GetUserPubKey start =================")
	result := map[string]interface{}{
		"user_id": "",
		"pub_key": "",
		"error":   "",
	}
	c.Data["json"] = result
	defer func() {
		err := recover()
		if nil != err {
			result["error"] = err
			c.ServeJSON()
		}
	}()
	auth.HandleLogin(c.Ctx.Input.RequestBody)
	key_map := cipher.GenerateRSAKeyPair()
	user_id := utils.GetUniqueKeys(1)[0]
	var items = map[string]interface{}{
		"sql": make([]string, 0),
		"len": 0,
	}
	var item = map[string]interface{}{
		"user_id":          user_id,
		"user_public_key":  key_map["public_key"],
		"user_private_key": key_map["private_key"],
	}
	items = str.GenInsertSql(items, item, "user_info")
	data_sql, _ := items["sql"].([]string)
	beego.Info(data_sql[0])
	o := orm.NewOrm()
	exe_result, err := o.Raw(data_sql[0]).Exec()
	beego.Info(fmt.Sprintf("insert执行结果: %s", exe_result))
	beego.Info(fmt.Sprintf("执行状态: %s", err))
	result["user_id"] = user_id
	result["pub_key"] = cipher.GetKey(key_map["public_key"])
	c.ServeJSON()
	beego.Info("================= GetUserPubKey end =================")
}

func (c *UserController) CancelAddUser() {
	beego.Info("================= CancelAddUser start =================")
	result := map[string]interface{}{
		"status": false,
		"error":  "",
	}
	c.Data["json"] = result
	defer func() {
		err := recover()
		if nil != err {
			result["error"] = err
			c.ServeJSON()
		}
	}()
	resp := auth.HandleLogin(c.Ctx.Input.RequestBody)
	user_id := utils.CheckFieldExists(resp, "user_id")
	sql := fmt.Sprintf("delete from user_info where user_id='%s'", user_id)
	beego.Info(sql)
	o := orm.NewOrm()
	exe_result, err := o.Raw(sql).Exec()
	beego.Info(fmt.Sprintf("delete执行结果: %s", exe_result))
	beego.Info(fmt.Sprintf("执行状态: %s", err))
	result["status"] = true
	c.ServeJSON()
	beego.Info("================= CancelAddUser end =================")
}

func (c *UserController) ConfirmAddUser() {
	beego.Info("================= ConfirmAddUser start =================")
	result := map[string]interface{}{
		"status": false,
		"error":  "",
	}
	c.Data["json"] = result
	defer func() {
		err := recover()
		if nil != err {
			result["error"] = err
			c.ServeJSON()
		}
	}()
	resp := auth.HandleLogin(c.Ctx.Input.RequestBody)
	user_id := utils.CheckFieldExists(resp, "user_id").(string)
	user_name := utils.CheckFieldExists(resp, "user_name").(string)
	user_pwd := utils.CheckFieldExists(resp, "user_pwd").(string)
	user_role := utils.CheckFieldExists(resp, "user_role").([]interface{})
	o := orm.NewOrm()
	var maps []orm.Params
	sql := fmt.Sprintf("select role_name from user_role where user_name='%s'", user_name)
	beego.Info(sql)
	o.Raw(sql).Values(&maps)
	add_role_path := []interface{}{}
	del_role_path := []string{}
	db_page_path := []interface{}{}
	for _, value := range maps {
		db_page_path = append(db_page_path, value["role_name"])
		if !utils.In(user_role, value["role_name"]) {
			del_role_path = append(del_role_path, value["role_name"].(string))
		}
	}
	for _, value := range user_role {
		if !utils.In(db_page_path, value) {
			add_role_path = append(add_role_path, value)
		}
	}
	save_user_role_map(user_id, user_name, user_pwd, add_role_path)
	where := "('" + strings.Join(del_role_path, "', '") + "')"
	sql = fmt.Sprintf("delete from user_role where user_name='%s' and role_name in %s", user_name, where)
	beego.Info(sql)
	exe_result, err := o.Raw(sql).Exec()
	beego.Info(fmt.Sprintf("delete执行结果: %s", exe_result))
	beego.Info(fmt.Sprintf("执行状态: %s", err))
	result["status"] = true
	c.ServeJSON()
	beego.Info("================= ConfirmAddUser end =================")
}

func save_user_role_map(user_id string, user_name string, user_pwd string, user_role []interface{}) {
	sql := fmt.Sprintf("update user_info set user_name='%s', user_pwd='%s' where user_id='%s'", user_name, user_pwd, user_id)
	beego.Info(sql)
	o := orm.NewOrm()
	exe_result, err := o.Raw(sql).Exec()
	beego.Info(fmt.Sprintf("update执行结果: %s", exe_result))
	beego.Info(fmt.Sprintf("执行状态: %s", err))
	var role_items = map[string]interface{}{
		"sql": make([]string, 0),
		"len": 0,
	}
	for _, role_name := range user_role {
		var food_item = map[string]interface{}{
			"user_role_id": utils.GetUniqueKey(),
			"user_name":    user_name,
			"role_name":    role_name.(string),
		}
		role_items = str.GenInsertSql(role_items, food_item, "user_role")
	}
	data_sql, _ := role_items["sql"].([]string)
	for _, role_item_v := range data_sql {
		beego.Info(role_item_v)
		exe_result, err := o.Raw(role_item_v).Exec()
		beego.Info(fmt.Sprintf("insert执行结果: %s", exe_result))
		beego.Info(fmt.Sprintf("执行状态: %s", err))
	}
}

func (c *UserController) DelUser() {
	beego.Info("================= DelUser start =================")
	result := map[string]interface{}{
		"status": false,
		"error":  "",
	}
	c.Data["json"] = result
	defer func() {
		err := recover()
		if nil != err {
			result["error"] = err
			c.ServeJSON()
		}
	}()
	resp := auth.HandleLogin(c.Ctx.Input.RequestBody)
	user_names := utils.CheckFieldExists(resp, "user_name").([]interface{})
	user_list := []string{}
	for _, value := range user_names {
		user_list = append(user_list, value.(string))
	}
	where := "('" + strings.Join(user_list, "', '") + "')"
	sql := fmt.Sprintf("delete from user_info where user_name in %s", where)
	beego.Info(sql)
	o := orm.NewOrm()
	exe_result, err := o.Raw(sql).Exec()
	beego.Info(fmt.Sprintf("delete执行结果: %s", exe_result))
	beego.Info(fmt.Sprintf("执行状态: %s", err))
	sql = fmt.Sprintf("delete from user_role where user_name in %s", where)
	beego.Info(sql)
	exe_result, err = o.Raw(sql).Exec()
	beego.Info(fmt.Sprintf("delete执行结果: %s", exe_result))
	beego.Info(fmt.Sprintf("执行状态: %s", err))
	result["status"] = true
	c.ServeJSON()
	beego.Info("================= DelUser end =================")
}

func (c *UserController) QueryUser() {
	beego.Info("================= QueryUser start =================")
	result := map[string]interface{}{
		"user_list": []interface{}{},
		"error":     "",
	}
	c.Data["json"] = result
	defer func() {
		err := recover()
		if nil != err {
			result["error"] = err
			c.ServeJSON()
		}
	}()
	auth.HandleLogin(c.Ctx.Input.RequestBody)
	sql := "select user_id as id, user_name from user_info where user_name<>''"
	beego.Info(sql)
	o := orm.NewOrm()
	var maps []orm.Params
	o.Raw(sql).Values(&maps)
	result["user_list"] = maps
	c.ServeJSON()
	beego.Info("================= QueryUser end =================")
}

func (c *UserController) QueryUserRole() {
	beego.Info("================= QueryUserRole start =================")
	result := map[string]interface{}{
		"user_role": []interface{}{},
		"error":     "",
	}
	c.Data["json"] = result
	defer func() {
		err := recover()
		if nil != err {
			result["error"] = err
			c.ServeJSON()
		}
	}()
	resp := auth.HandleLogin(c.Ctx.Input.RequestBody)
	user_name := utils.CheckFieldExists(resp, "user_name")
	sql := fmt.Sprintf("select role_name from user_role where user_name='%s'", user_name)
	beego.Info(sql)
	o := orm.NewOrm()
	var maps []orm.Params
	o.Raw(sql).Values(&maps)
	user_role := []interface{}{}
	for _, role := range maps {
		user_role = append(user_role, role["role_name"])
	}
	result["user_role"] = user_role
	c.ServeJSON()
	beego.Info("================= QueryUserRole end =================")
}

func (c *UserController) AlterPwd() {
	beego.Info("================= AlterPwd start =================")
	result := map[string]interface{}{
		"status": false,
		"error":  "",
	}
	c.Data["json"] = result
	defer func() {
		err := recover()
		if nil != err {
			result["error"] = err
			c.ServeJSON()
		}
	}()
	resp := auth.HandleLogin(c.Ctx.Input.RequestBody)
	user_name := utils.CheckFieldExists(resp, "userName").(string)
	user_pwd := utils.CheckFieldExists(resp, "user_pwd").(string)
	sql := fmt.Sprintf("update user_info set user_pwd='%s' where user_name='%s'", user_pwd, user_name)
	beego.Info(sql)
	o := orm.NewOrm()
	exe_result, err := o.Raw(sql).Exec()
	beego.Info(fmt.Sprintf("update执行结果: %s", exe_result))
	beego.Info(fmt.Sprintf("执行状态: %s", err))
	result["status"] = true
	c.ServeJSON()
	beego.Info("================= AlterPwd end =================")
}
